package com.zunipe.accounts.database.handler;

import android.util.Log;

import com.zunipe.accounts.AccountApplication;
import com.zunipe.accounts.database.dao.AccountDao;
import com.zunipe.accounts.database.entity.Account;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class AccountHandler {
    private final AccountDao accountDao;

    public AccountHandler() {
        accountDao = AccountApplication.getInstance().getAccountDao();
    }

    public boolean hasTouristDataAvailable() {
        return !accountDao.findByUserId(0).isEmpty();
    }

    public void saveTouristData(int userId) {
        accountDao.updateUserId(0, userId);
    }

    public void deleteTouristData() {
        accountDao.removeByUserId(0);
    }

    public void deleteById(int id) {
        accountDao.removeById(id);
    }

    public void updateAccount(Account account) {
        accountDao.update(account);
    }

    public Account getAccountById(int id) {
        return accountDao.findById(id);
    }

    public double getExpensesAmountByDate(String date) {
        return accountDao.sumExpensesAmountByDate(date, AccountApplication.getInstance().getUserId());
    }

    public double getIncomeAmountByDate(String date) {
        return accountDao.sumIncomeAmountByDate(date, AccountApplication.getInstance().getUserId());
    }

    public Map<String, List<Account>> getList(String date) {
        List<Account> accounts = accountDao.findByDate(date, AccountApplication.getInstance().getUserId());
        for (Account account : accounts) {
            Log.d("TEST", account.toString());
        }
        return groupAccountByDate(accounts);
    }

    private Map<String, List<Account>> groupAccountByDate(List<Account> list) {
        Map<String, List<Account>> groupedData = new HashMap<>();
        for (Account account : list) {
            String dayDate = account.getDate();
            if (!groupedData.containsKey(dayDate)) {
                groupedData.put(dayDate, new ArrayList<>());
            }
            groupedData.get(dayDate).add(account);
        }
        return groupedData;
    }

    public int addAccount(Account account) {
        return accountDao.insert(account);
    }
}
